package controllers;

import static util.FindFoodUtil.empty;
import models.User;
import models.ZipcodeGeo;
import play.cache.Cache;
import play.data.validation.Required;
import play.i18n.Messages;
import play.mvc.Controller;
import play.mvc.With;
import util.GoogleGeocode.GeocodeException;

@With({Common.class, Authorize.class})
public class Profile extends Controller {

	public static void edit() {
		/* If this is the user's first visit, Common's loader won't load a User, so we'll
		 * create a phony User to display the signed-in OpenID.
		 */
		if (renderArgs.get("user") == null) {
			String openId = session.get("openid");
			User user = new User();
			user.setOpenId(openId);
			renderArgs.put("user", user);
		}
		render();
	}

	public static void save(
			@Required(message = "required.username") String username, String home) {
		ZipcodeGeo zipgeo = null;
		if (!empty(home)) {
			try {
				zipgeo = ZipcodeGeo.get(home);
			} catch (GeocodeException e) {
				// Leave zipgeo null.
			}
			if (zipgeo == null)
				validation.addError("home", Messages.get("zipcode.invalid"));
		}

		if (validation.hasErrors()) {
			validation.keep();
			edit();
		}

		User user = User.getUser(session);
		if (user == null) {
			user = new User();
			user.setOpenId(session.get("openid"));
		}
		user.setUsername(username);
		user.setHome(zipgeo);
		user.save();
		Cache.set("user-" + user.getOpenId(), user);
		edit();
	}
}
